<template>
  <div style="margin: -20px">
    <div v-if="showUpload">
      <upload-page app-type-code="03" @backHandle="backHandle" />
    </div>
    <el-row v-else type="flex" class="app-store">
      <el-col :span="5" style="min-width: 280px">
        <div
          class="app-block bg-white py-6"
          style="border-right: 1px solid #edf2f9; height: calc(100vh - 50px)"
        >
          <div class="mb-3 px-5 flex items-center justify-between">
            <h2 class="inline-block">{{ $t('menu.M_1040000402') }}</h2>
            <!--            <el-input-->
            <!--              v-model.trim="key_word"-->
            <!--              style="width:60%;margin-left: 20px;"-->
            <!--              placeholder="Please enter content"-->
            <!--            />-->
            <!--<div class="flex items-center">-->
            <!--              <button @click="handleSearch">-->
            <!--                <svg-icon icon-class="search" class="text-xl mx-3 text-secondary" />-->
            <!--              </button>-->
            <el-button
              v-if="isAuth('1040000402.MANAGE') && !showUpload"
              class="w-8"
              type="primary"
              @click="uploadHandle"
            >
              <svg-icon icon-class="Plus" />
            </el-button>
            <!--</div>-->
          </div>
          <el-scrollbar style="height: 100%" wrap-style="overflow-x:hidden;">
            <el-empty v-if="!categoryList[0]" />
            <div v-else>
              <ul class="group-list">
                <li
                  v-for="cate in categoryList"
                  :key="cate.categoryId"
                  :class="{
                    active:
                      clickCategory == null
                        ? false
                        : clickCategory.appFileId === cate.appFileId
                  }"
                  @click="changeAppDataList(cate)"
                >
                  <div class="flex items-center justify-between">
                    <div class="flex items-center">
                      <div class="pr-4">
                        <img class="app-icon" :src="iconView(cate.iconUrl)" />
                      </div>
                      <div>
                        <div style="font-size:14px;line-height:22px;font-weight:600;">{{ cate.appName }}</div>
                        <div  style="font-size:14px;line-height:22px;font-weight:500;">
                          {{ cate.version }}
                        </div>
                      </div>
                    </div>
                  </div>
                </li>
              </ul>
            </div>
          </el-scrollbar>
        </div>
      </el-col>
      <el-col :span="19">
        <el-card
          shadow="never"
          :body-style="{ padding: '0px' }"
          :page-size="pageSize"
          :total="totalPage"
          :current-page="pageNo"
          @current-change="currentChangeHandle"
        >
          <el-table v-loading="dataListLoading" :data="appList" stripe>
            <el-table-column type="expand">
              <template v-slot="{ row }">
                <el-descriptions title="" :column="2" border>
                  <el-descriptions-item :label="$t('sysapp.appName')">{{
                    row.appName
                  }}</el-descriptions-item>
                  <el-descriptions-item :label="$t('sysapp.appPackageName')">{{
                    row.appPackageName
                  }}</el-descriptions-item>
                  <el-descriptions-item :label="$t('sysapp.fileSize')"
                    >{{
                      (row.fileLength / 1024 / 1024).toFixed(2)
                    }}
                    MB</el-descriptions-item
                  >
                  <el-descriptions-item :label="$t('sysapp.fileMd5')">{{
                    row.fileMd5
                  }}</el-descriptions-item>
                  <el-descriptions-item :label="$t('sysapp.version')">{{
                    row.versionName
                  }}</el-descriptions-item>
                  <el-descriptions-item :label="$t('sysapp.uploadTime')">{{
                    uploadFormatDate(row)
                  }}</el-descriptions-item>
                  <!-- <el-descriptions-item :label="$t('sysapp.supportDevice')">
                    <el-checkbox v-model="row.modeHand === 1" disabled>{{
                      $t('sysapp.handHeld')
                    }}</el-checkbox>
                    <el-checkbox v-model="row.modeHd === 1" disabled>{{
                      $t('sysapp.hd')
                    }}</el-checkbox>
                  </el-descriptions-item> -->
                  <el-descriptions-item :label="$t('sysapp.updateMode')">
                    <el-tag
                      v-if="row.forceUpdate === 0"
                      size="small"
                      :class="'flow-state-tag-' + row.forceUpdate"
                      >{{ $t('sysapp.normalUpdate') }}</el-tag
                    >
                    <el-tag
                      v-if="row.forceUpdate === 1"
                      size="small"
                      :class="'flow-state-tag-' + row.forceUpdate"
                      >{{ $t('sysapp.silentUpdate') }}</el-tag
                    >
                  </el-descriptions-item>
                  <el-descriptions-item :label="$t('sysapp.installMode')">
                    <el-tag
                      v-if="row.deleteUpdate === 0"
                      size="small"
                      :class="'flow-state-tag-' + row.deleteUpdate"
                      >{{ $t('sysapp.patchInstall') }}</el-tag
                    >
                    <el-tag
                      v-if="row.deleteUpdate === 1"
                      size="small"
                      :class="'flow-state-tag-' + row.deleteUpdate"
                      >{{ $t('sysapp.deleteInstall') }}</el-tag
                    >
                  </el-descriptions-item>
                  <el-descriptions-item :label="$t('sysapp.production')">
                    <el-tag
                      v-if="row.versionStyle === 0"
                      size="small"
                      :class="`flow-state-tag-${row.versionStyle}`"
                      >{{ $t('sysapp.grayscaleStyle') }}</el-tag
                    >
                    <el-tag
                      v-if="row.versionStyle === 1"
                      size="small"
                      :class="`flow-state-tag-${row.versionStyle}`"
                      >{{ $t('sysapp.productionStyle') }}</el-tag
                    >
                  </el-descriptions-item>
                  <el-descriptions-item :label="$t('sysapp.remark')">{{
                    row.remark
                  }}</el-descriptions-item>
                </el-descriptions>
              </template>
            </el-table-column>
            <el-table-column prop="versionName" :label="$t('sysapp.version')" />
            <el-table-column
              prop="installDevCnt"
              :label="$t('sysapp.installDevCount')"
            />
            <el-table-column
              prop="forceUpdate"
              :label="$t('sysapp.updateMode')"
            >
              <template v-slot="scope">
                <el-tag
                  v-if="scope.row.forceUpdate === 0"
                  size="small"
                  :class="`flow-state-tag-${scope.row.forceUpdate}`"
                  >{{ $t('sysapp.normalUpdate') }}</el-tag
                >
                <el-tag
                  v-if="scope.row.forceUpdate === 1"
                  size="small"
                  :class="`flow-state-tag-${scope.row.forceUpdate}`"
                  >{{ $t('sysapp.silentUpdate') }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column
              prop="deleteUpdate"
              :label="$t('sysapp.installMode')"
            >
              <template v-slot="scope">
                <el-tag
                  v-if="scope.row.deleteUpdate === 0"
                  size="small"
                  :class="`flow-state-tag-${scope.row.deleteUpdate}`"
                  >{{ $t('sysapp.patchInstall') }}</el-tag
                >
                <el-tag
                  v-if="scope.row.deleteUpdate === 1"
                  size="small"
                  :class="`flow-state-tag-${scope.row.deleteUpdate}`"
                  >{{ $t('sysapp.deleteInstall') }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column
              prop="versionStyle"
              :label="$t('sysapp.production')"
            >
              <template v-slot="scope">
                <el-tag
                  v-if="scope.row.versionStyle === 0"
                  size="small"
                  :class="`flow-state-tag-${scope.row.versionStyle}`"
                  >{{ $t('sysapp.grayscaleStyle') }}</el-tag
                >
                <el-tag
                  v-if="scope.row.versionStyle === 1"
                  size="small"
                  :class="`flow-state-tag-${scope.row.versionStyle}`"
                  >{{ $t('sysapp.productionStyle') }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column prop="creTime" :label="$t('sysapp.uploadTime')">
              <template v-slot="scope">
                <div :title="timeFilter(scope.row.creTime)">
                  {{ dateFilter(scope.row.creTime) }}
                  {{ scope.row.creTime ? '' : '-' }}
                </div>
              </template>
            </el-table-column>
            <el-table-column width="75px">
              <template v-slot="scope">
                <el-dropdown class="align-middle" trigger="click">
                  <el-button text class="w-8">
                    <svg-icon icon-class="MoreFilled" />
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu :loading="loading">
                      <el-dropdown-item
                        v-if="isAuth('1040000402.MANAGE')"
                        @click="downloadHandle(scope.row)"
                      >
                        <svg-icon icon-class="Download" />
                        {{ $t('common.downloadBtn') }}
                      </el-dropdown-item>
                      <el-dropdown-item
                        @click="terminalListHandle(scope.row)"
                        v-show="scope.row.versionStyle === 0"
                      >
                        <svg-icon icon-class="Document" />
                        {{ $t('sysapp.terminalListBtn') }}
                      </el-dropdown-item>
                      <el-dropdown-item
                        v-if="isAuth('1040000402.MANAGE')"
                        v-show="scope.row.versionStyle === 0"
                        @click="productionReleaseHandle(scope.row)"
                      >
                        <svg-icon icon-class="Position" />
                        {{ $t('sysapp.productionReleaseBtn') }}
                      </el-dropdown-item>
                      <el-dropdown-item
                        v-if="isAuth('1040000402.MANAGE')"
                        @click="deleteHandle(scope.row)"
                      >
                        <svg-icon icon-class="Delete" />
                        {{ $t('common.deleteBtn') }}
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>

                <!-- <el-tooltip
                  class="item"
                  effect="dark"
                  :content="$t('common.downloadBtn')"
                  placement="top"
                >
                  <el-button
                    v-if="isAuth('1040000402.MANAGE')"
                    class="tag-green"
                    type="text"
                    :loading="loading"
                    icon="el-icon-bottom"
                    @click="downloadHandle(scope.row)"
                  />
                </el-tooltip> -->
                <!-- <el-tooltip
                  class="item"
                  effect="dark"
                  :content="$t('sysapp.terminalListBtn')"
                  placement="top"
                >
                  <el-button
                    v-show="scope.row.versionStyle === 0"
                    style="color: #556de7"
                    :loading="loading"
                    icon="el-icon-s-order"
                    @click="terminalListHandle(scope.row)"
                  />
                </el-tooltip> -->
                <!-- <el-tooltip
                  class="item"
                  effect="dark"
                  :content="$t('sysapp.productionReleaseBtn')"
                  placement="top"
                >
                  <el-button
                    v-if="isAuth('1040000402.MANAGE')"
                    v-show="scope.row.versionStyle === 0"
                    style="color: #556de7"
                    :loading="loading"
                    icon="el-icon-s-promotion"
                    type="text"
                    @click="productionReleaseHandle(scope.row)"
                  >
                  </el-button>
                </el-tooltip> -->
                <!-- <el-tooltip
                  class="item"
                  effect="dark"
                  :content="$t('common.deleteBtn')"
                  placement="top"
                >
                  <el-button
                    v-if="isAuth('1040000402.MANAGE')"
                    style="color: #dc143c"
                    type="text"
                    :loading="loading"
                    icon="el-icon-delete"
                    @click="deleteHandle(scope.row)"
                  />
                </el-tooltip> -->
              </template>
            </el-table-column>
          </el-table>
          <grayscale
            ref="grayscale"
            v-model="grayscaleVisible"
            @close="grayscaleVisible = false"
            @refreshDataList="backHandle"
          />
        </el-card>
      </el-col>
    </el-row>
    <upload
      v-if="uploadVisible"
      ref="upload"
      @refreshDataList="getAppDataList"
      @close="uploadVisible = false"
    />
  </div>
</template>

<script>
import { timeFilter, dateFilter } from '@/filters/index'
import {
  getSysAppList,
  getAppInfoPage,
  downloadApp,
  deleteApp,
  sysProductionRelease
} from '@/api/sysapp'
import { formatDate } from '@/utils/formatDate'
import uploadPage from './upload.vue'
import Grayscale from './components/grayscale'
import { isAuth } from '@/utils'

export default {
  components: {
    uploadPage,
    Grayscale
  },
  data() {
    return {
      dataForm: {
        appName: '',
        developerName: '',
        chargeStrategy: ''
      },
      uploadVisible: false,
      showUpload: false,
      categoryList: [],
      appList: [],
      loading: false,
      dataListLoading: false,
      grayscaleVisible: false,
      noMore: false,
      busy: false,
      pageNo: 1,
      pageSize: 10,
      rows: 0,
      clickCategory: null,
      clickAppId: 0,
      paginationShow: true,
      pageIndex: 1,
      totalPage: 0
    }
  },
  computed: {
    colHeight() {
      return this.$store.state.common.documentClientHeight - 82 - 80
    },
    categoryTotal() {
      // eslint-disable-next-line no-return-assign
      return this.categoryList !== []
        ? this.categoryList.reduce(
            (total, category) => (total += category.appCount),
            0
          )
        : 0
    }
  },
  mounted() {
    this.getCategoryDataList()
    this.getAppDataList()
  },
  methods: {
    isAuth,
    timeFilter,
    dateFilter,
    iconView(icon) {
      if (icon) {
        return import.meta.env.VITE_APP_BASE_API + icon
      }
      return require('@/assets/img/Android.png')
    },
    getCategoryDataList() {
      this.loading = false
      getSysAppList('03')
        .then((data) => {
          this.categoryList = data
        })
        .catch((e) => {
          this.loading = false
          this.$confirmError(e)
        })
    },
    getAppDataList(cate) {
      this.loading = false
      this.dataListLoading = true
      this.clickCategory = cate
      const packageName = cate == null ? null : cate.appPackageName
      getAppInfoPage({
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        packageName: packageName
      })
        .then((data) => {
          console.log(data)
          this.appList = data.data
          this.totalPage = data.rows
        })
        .catch((e) => {
          this.$confirmError(e)
          this.appList = []
          this.totalPage = 0
        })
        .finally(() => {
          this.dataListLoading = false
        })
    },
    changeAppDataList(cate) {
      this.pageNo = 1
      this.getAppDataList(cate)
    },
    loadMore() {
      if (this.pageNo > this.rows / this.pageSize) {
        this.loading = false
        this.busy = true
        this.noMore = true
        return
      }
      this.loading = true
      this.busy = false
      this.pageNo = this.pageNo + 1
      getAppInfoPage({
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        appCategoryId: this.clickCategoryId
      })
        .then((data) => {
          if (this.appList.length >= this.rows) {
            this.loading = false
            this.busy = true
            this.noMore = true
          } else {
            setTimeout(() => {
              this.appList = this.appList.concat(data.data.data)
              this.loading = false
            }, 1000)
          }
        })
        .catch((e) => {
          this.loading = false
          this.$confirmError(e)
        })
    },
    showDetailHandle(appId, appVersionId) {
      this.$router.push({
        name: 'app-detail',
        query: {
          appId: appId,
          appVersionId: appVersionId
        }
      })
    },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageNo = 1
      this.getAppDataList(this.clickCategory)
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageNo = val
      this.getAppDataList(this.clickCategory)
    },
    uploadHandle() {
      this.showUpload = true
    },
    downloadHandle(row) {
      const appFileId = row.appFileId
      this.loading = true
      downloadApp(appFileId)
        .then((data) => {
          console.log(row)
          this.loading = false
          if (data.url !== null) {
            // const link = document.createElement('a')
            // link.style.display = 'none'
            window.open(data.url, '_blank')
            // link.setAttribute('href', data.url)
            // link.click()
          } else {
            this.$message({
              type: 'error',
              message: this.$t('sysapp.downloadFailed')
            })
          }
        })
        .catch((e) => {
          this.$confirmError(e)
          this.loading = false
        })
    },
    deleteHandle(row) {
      this.$confirm(this.$t('sysapp.deleteConfirm'), '', {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        console.log(`${row.appFileId}  ${row.operatorId}`)
        this.loading = true
        deleteApp(row.appFileId)
          .then((data) => {
            this.$message({
              type: 'success',
              message: this.$t('common.operate_success')
            })
            this.loading = false
            this.changeAppDataList(this.clickCategory)
            this.getCategoryDataList()
          })
          .catch((e) => {
            this.$confirmError(e)
            this.loading = false
          })
      })
      console.log(row)
    },
    uploadFormatDate(row) {
      return formatDate(row.creTime, 'YYYY-MM-DD  HH:mm:ss')
    },
    backHandle(refresh) {
      this.showUpload = false
      if (refresh) {
        this.pageNo = 1
        this.getCategoryDataList()
        this.getAppDataList()
      }
    },
    terminalListHandle(row) {
      this.grayscaleVisible = true
      this.$nextTick(() => {
        this.$refs.grayscale.init(row.appFileId)
      })
    },
    productionReleaseHandle(row) {
      this.$confirm('Are you sure to Release the application?', '', {
        confirmButtonText: this.$t('common.confirm'),
        cancelButtonText: this.$t('common.cancel'),
        type: 'warning'
      }).then(() => {
        this.loading = true
        sysProductionRelease(row.appFileId)
          .then((res) => {
            this.loading = false
            if (res) {
              this.$message({
                type: 'success',
                message: 'Release version successfully!'
              })
              this.getAppDataList(this.clickCategory)
              this.getCategoryDataList()
            }
          })
          .catch((e) => {
            this.$confirmError(e)
            this.loading = false
          })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-block {
  .group-list {
    li {
      color: #555555;
      border-top: 1px solid #f5f7fa;
      cursor: pointer;
      padding: 16px;
      &:first-child {
        border-top: 1px solid #f5f7fa;
      }
      &.active {
        background: #f5f7fa;
        // color: #12263f;
        // font-size: 1.1em;
        // font-weight: 700;
      }
      .app-icon {
        width: 40px;
        height: 40px;
      }
    }
  }
}
.app-store {
  .loadTxt {
    text-align: center;
    width: 100%;
    // z-index: 99;
  }
  .rightPart {
    flex-wrap: wrap;
    align-content: flex-start;
    overflow: auto;
    .app-item {
      height: 240px;
      .el-image {
        width: 100px;
        height: 100px;
        border-radius: 5px;
      }
      cursor: pointer;
      text-align: center;
      margin: 2px 0 10px;
      transition: all 0.5s;
      p {
        margin: 0;
        line-height: 1.2rem;
        font-size: small;
      }
      &:hover {
        transform: scale(1.1);
      }
    }
  }
}
</style>
